<template>
    <el-form :inline="true">
        <el-form-item label="角色">
            <el-select placeholder="选择角色" style="width: 100px" v-model="searchRequest.roleId" :options="roleData"
                :props="roleProps">
            </el-select>
        </el-form-item>
        <el-form-item label="状态">
            <el-select placeholder="选择状态" style="width: 100px" v-model="searchRequest.status" :options="yhztData"
                :props="yhztProps">
            </el-select>
        </el-form-item>
        <el-form-item label="关键字">
            <el-input v-model="searchRequest.keyword" placeholder="请输入查询关键字" autocomplete="off" />
        </el-form-item>
        <el-form-item>
            <el-button type="primary" @click="onSearch" v-permission="'user:query'"> 筛选 </el-button>
            <el-button type="info" @click="onReset" v-permission="'user:query'"> 重置 </el-button>
            <el-divider direction="vertical" />
            <el-button type="success" @click="onAdd" v-permission="'user:add'"> 添加 </el-button>
        </el-form-item>
    </el-form>
    <el-table :data="tableData" style="width: 100%">
        <el-table-column prop="roleName" label="角色" width="150" />
        <el-table-column prop="userName" label="用户名" width="150" show-overflow-tooltip />
        <el-table-column prop="nickName" label="昵称" width="*" show-overflow-tooltip />
        <el-table-column prop="email" label="邮箱" width="200" show-overflow-tooltip />
        <el-table-column prop="tel" label="电话" width="120" />
        <!-- <el-table-column prop="bak" label="备注" width="*" show-overflow-tooltip /> -->
        <el-table-column prop="status" label="状态" width="80">
            <template #default="scope">
                <span v-if="yhztDict[scope.row.status]">{{ yhztDict[scope.row.status].name }}</span>
                <span v-else>未知状态</span>
            </template>
        </el-table-column>
        <el-table-column label="操作" width="230">
            <template #default="scope">
                <el-button link type="primary" @click="onDelete(scope.row)" v-permission="'user:delete'">删除</el-button>
                <el-button link type="primary" @click="onEdit(scope.row)" v-permission="'user:edit'">修改</el-button>
                <el-button link type="primary" @click="onResetPwd(scope.row)"
                    v-permission="'user:reset'">重置密码</el-button>
                <el-button link type="primary" @click="onView(scope.row)">查看</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 5px" :page-size="searchRequest.pageSize" :total="tableTotal"
        :current-page="searchRequest.pageIndex" @current-change="onPageChange" />
    <!--修改或添加弹窗-->
    <el-dialog v-model="dialogEditVisible" :title="dialogEditTitle" width="400px" @close="dialogEditVisible = false">
        <el-form ref="userEditDataRef" :model="userEditData" :rules="rules" label-width="auto">
            <el-form-item label="用户名" prop="userName">
                <el-input autocomplete="off" v-model="userEditData.userName" placeholder="请输入用户名(不超过20个字符的英文或数字)" />
            </el-form-item>
            <el-form-item label="角色" prop="roleId">
                <el-select v-model="userEditData.roleId" :options="roleData" :props="roleProps" placeholder="选择角色" />
            </el-form-item>
            <el-form-item label="昵称" prop="nickName">
                <el-input autocomplete="off" v-model="userEditData.nickName" placeholder="请输入昵称(不超过20个字符的中英文、数字)" />
            </el-form-item>
            <el-form-item label="邮箱" prop="email">
                <el-input autocomplete="off" v-model="userEditData.email" placeholder="请输入邮箱(不超过20个字符)" />
            </el-form-item>
            <el-form-item label="电话" prop="tel">
                <el-input autocomplete="off" v-model="userEditData.tel" placeholder="请输入手机号" />
            </el-form-item>
            <el-form-item label="状态" prop="status" v-if="dialogEditFlag === DialogType.EDIT">
                <el-select placeholder="选择状态" v-model="userEditData.status" :options="yhztData" :props="yhztProps">
                </el-select>
            </el-form-item>
            <el-form-item label="备注" prop="bak">
                <el-input type="textarea" autocomplete="off" v-model="userEditData.bak"
                    placeholder="请输入备注(不超过200个字符)" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div>
                <el-button @click="dialogEditVisible = false">取消</el-button>
                <el-button type="primary" @click="onSave(userEditDataRef)"> 确定 </el-button>
            </div>
        </template>
    </el-dialog>
    <!--查看弹窗-->
    <el-dialog v-model="dialogViewVisible" title="用户信息" width="400px" @close="dialogViewVisible = false">
        <el-form :model="userViewData" label-width="auto">
            <el-form-item label="角色">
                {{ userViewData.roleName }}
            </el-form-item>
            <el-form-item label="用户名">
                {{ userViewData.userName }}
            </el-form-item>
            <el-form-item label="昵称">
                {{ userViewData.nickName }}
            </el-form-item>
            <el-form-item label="邮箱">
                {{ userViewData.email }}
            </el-form-item>
            <el-form-item label="电话">
                {{ userViewData.tel }}
            </el-form-item>
            <el-form-item label="状态">
                {{ userViewData.statusName }}
            </el-form-item>
            <el-form-item label="备注">
                <el-text line-clamp="2">
                    {{ userViewData.bak }}
                </el-text>
            </el-form-item>

        </el-form>
    </el-dialog>
</template>
<script setup>
import { ref, onMounted, reactive } from 'vue'
import api from '@/apis/api'
import { ElMessage, ElMessageBox } from 'element-plus'
import { DialogType, PageConfig, StorageKey } from '@/constant'
import appStorage from '@/stores/storage'

//数据字典
const yhztDict = {}
const yhztData = ref([])
const yhztProps = {
    value: 'code',
    label: 'name',
}
//角色数据
const roleData = ref([])
const roleDict = {}
const roleProps = {
    value: 'roleId',
    label: 'roleName',
}
//筛选
const searchRequest = reactive({
    roleId: null,
    status: null,
    keyword: null,
    pageIndex: 1,
    pageSize: PageConfig.PAGE_SIZE
})
//表数据
const tableData = ref([])
const tableTotal = ref(0)

//用户数据

const userEditDataRef = ref()
const userEditData = reactive({
    userId: null,
    userName: null,
    roleId: null,
    nickName: null,
    email: null,
    tel: null,
    bak: null,
    status: null,
})
const rules = reactive({
    userName: [{ required: true, pattern: /^[A-Za-z0-9]+$/, message: "请输入用户名(英文或数字)", trigger: "blur" }, { max: 20, message: "用户名不超过20个字符", trigger: "blur" }],
    roleId: [{ required: true, message: "请选择角色", trigger: "blur" }],
    nickName: [{ required: true, pattern: /^[\u4E00-\u9FA5A-Za-z0-9]+$/, message: "请输入昵称(中英文、数字)", trigger: "blur" }, { max: 20, message: "昵称不超过20个字符", trigger: "blur" }],
    email: [{ required: true, type: 'email', message: "请输入正确的邮箱", trigger: "blur" }, { max: 20, message: "邮箱不超过20个字符", trigger: "blur" }],
    tel: [{ required: true, pattern: /^(((13|14|15|17|18)\d{9}))$/, message: "请输入正确的手机号码", trigger: "blur" }],
    bak: [{ max: 200, message: "备注不超过200个字符", trigger: "blur" }]
});
//弹窗
const userViewData = reactive({
    userName: null,
    roleName: null,
    nickName: null,
    email: null,
    tel: null,
    bak: null,
    statusName: null,
})
const dialogViewVisible = ref(false)
const dialogEditTitle = ref('用户信息')
const dialogEditVisible = ref(false)
const dialogEditFlag = ref(DialogType.VIEW)//dialog模式，view、add、edit
onMounted(async () => {
    try {
        //从缓存获取数据字典
        let yhzt = appStorage.getSession(StorageKey.DICT)['YHZT']
        if (yhzt != null) {
            //需将数组转字典            
            for (let item of yhzt.children) {
                yhztDict[item.code] = item
            }            
            //筛选选项
            yhztData.value = yhzt.children
        }
        loadRole()
        loadTable()
    } catch (error) {
        console.error('数据加载失败:', error)
    }
})

async function loadRole() {
    api.role.list(resp => {
        roleData.value = resp.data
        for (let role of resp.data) {
            roleDict[role.roleId] = role
        }
    })
}
async function loadTable() {
    api.user.pageList(searchRequest.pageIndex, PageConfig.PAGE_SIZE, searchRequest.keyword, searchRequest.status, searchRequest.roleId, resp => {
        tableData.value = resp.data
        tableTotal.value = resp.rows
    })
}
async function onSearch() {
    searchRequest.pageIndex = 1
    loadTable()
}
async function onReset() {
    searchRequest.roleId = null
    searchRequest.keyword = null
    searchRequest.status = null
    searchRequest.pageIndex = 1
    loadTable()
}
async function onPageChange(pageIndex) {
    searchRequest.pageIndex = pageIndex
    loadTable()
}
//查看
async function onView(row) {
    userViewData.userName = row.userName
    userViewData.roleName = row.roleName
    userViewData.nickName = row.nickName
    userViewData.email = row.email
    userViewData.tel = row.tel
    userViewData.bak = row.bak
    userViewData.statusName = yhztDict[row.status]?.name
    dialogViewVisible.value = true
}
//删除
async function onDelete(row) {
    // console.log(row)
    ElMessageBox.confirm('确定删除?', '确认',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        })
        .then(() => {
            //确认
            api.user.delete(row.userId, resp => {
                onReset()
            })
        })
        .catch(() => {
            //取消
        })
}
//添加
async function onAdd() {
    dialogEditTitle.value = '添加用户'
    dialogEditFlag.value = DialogType.ADD
    clearForm()
    dialogEditVisible.value = true
}
//修改
async function onEdit(row) {
    dialogEditTitle.value = '修改用户信息'
    dialogEditFlag.value = DialogType.EDIT

    userEditData.userId = row.userId
    userEditData.userName = row.userName
    userEditData.roleId = row.roleId
    userEditData.nickName = row.nickName
    userEditData.email = row.email
    userEditData.tel = row.tel
    userEditData.bak = row.bak
    userEditData.status = row.status

    dialogEditVisible.value = true
}
//重置密码
async function onResetPwd(row) {
    api.user.resetPwd(row.userId, resp => {
        ElMessage('重置成功')
    })
}
//清空表单
async function clearForm() {
    userEditData.userId = null
    userEditData.userName = null
    userEditData.roleId = null
    userEditData.nickName = null
    userEditData.email = null
    userEditData.tel = null
    userEditData.bak = null
}
//保存
async function onSave(formEl) {

    if (!formEl) return
    await formEl.validate((valid, fields) => {
        if (valid) {
            if (dialogEditFlag.value == DialogType.ADD) {
                //添加
                api.user.add(userEditData.roleId, userEditData.userName, userEditData.nickName, userEditData.email, userEditData.tel, userEditData.bak, resp => {
                    clearForm()
                    ElMessage('添加成功')
                    onReset()//重新加载
                    dialogEditVisible.value = false
                })
            }
            else {
                //修改
                api.user.edit(userEditData.userId, userEditData.roleId, userEditData.nickName, userEditData.email, userEditData.tel, userEditData.bak, userEditData.status, resp => {

                    clearForm()
                    ElMessage('修改成功')
                    onReset()//重新加载
                    dialogEditVisible.value = false
                })
            }
        }
    })
}

</script>
